import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { createRouter, createWebHashHistory } from "vue-router";
import Routes from "./routers";
import pinia from "@/store";
import { UseUserStore } from "@/store/modules";
import setting from "@/setting";

let userStore = UseUserStore(pinia);

nprogress.configure({ showSpinner: false });

let router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/404",
      component: () => import("@/views/404/index.vue"),
      name: "404",
      meta: {
        title: "404",
      },
    },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/404",
      name: "any",
      meta: {
        title: "任意路由",
      },
    },
    {
      path: "/login",
      component: () => import("@/views/login/index.vue"),
      name: "login",
      meta: {
        title: "登录",
      },
    },
    {
      path: "/screen",
      component: () => import("@/views/screen/index.vue"),
      name: "screen",
      meta: {
        title: "数据大屏",
      },
    },
    {
      path: "/",
      component: () => import("@/components/layout.vue"),
      name: "layout",
      redirect: "/home",
      children: Routes,
    },
  ],
  // 滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

// 路由守卫
router.beforeEach((to, _, next) => {
  document.title = to.meta.title + ` | ${setting.title}`;
  nprogress.start();
  let token = userStore.token;
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      next();
      // if (username) {
      //   next();
      // } else {
      //   try {
      //     await userStore.userInfo();
      //     next({ ...to });
      //   } catch (error) {
      //     await userStore.userLogout();
      //     next({ path: "/login", query: { redirect: to.path } });
      //   }
      // }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
router.afterEach(() => {
  nprogress.done();
});

export default router;
